package controller

import (
	"fmt"
	"net/http"

	"gitee.com/liu_deping/gin-vue/common"
	"gitee.com/liu_deping/gin-vue/dao"
	"gitee.com/liu_deping/gin-vue/db"
	"gitee.com/liu_deping/gin-vue/dto"
	"gitee.com/liu_deping/gin-vue/model"
	"gitee.com/liu_deping/gin-vue/response"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

func Register(ctx *gin.Context) {

	//1.获取参数
	name := ctx.PostForm("name")
	password := ctx.PostForm("password")
	phone := ctx.PostForm("phone")

	//2.数据校验
	if len(phone) != 11 { //手机号不是11位
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "应输入11位手机号")
		return
	}

	if len(password) < 8 { //密码小于8位字符
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码不能小于8位字符")
		return
	}

	//3.表单验证
	if dao.IsPhoneExist(phone) { //手机号已注册
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "该手机号已注册")
		return
	}

	if len(name) == 0 { //没有给用户名:默认："用户+phone"
		name = fmt.Sprintf("用户%s", phone)
	}

	//4.创建用户
	//注意：创建用户时密码需要加密
	//加密：
	hasedPassword, err := bcrypt.GenerateFromPassword([]byte(password), len(password))
	if err != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "加密出错")
		return
	}
	user := model.User{
		Name:     name,
		Password: string(hasedPassword),
		Phone:    phone,
	}
	db.DB.Create(&user)

	//5.返回结果
	response.Success(ctx, nil, "注册成功")
}

func Login(ctx *gin.Context) {
	//1.获取参数
	phone := ctx.PostForm("phone")
	password := ctx.PostForm("password")

	//2.验证数据格式
	if phone == "" {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "手机号不能为空")
		return
	}
	if password == "" {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "密码不能为空")
		return
	}
	if len(phone) != 11 { //手机号不是11位
		response.Response(ctx, http.StatusBadRequest, 401, nil, "手机号必须为11位数字")
		return
	}

	if len(password) < 8 { //密码小于8位字符
		response.Response(ctx, http.StatusBadRequest, 401, nil, "密码必须大于8位字符")
		return
	}

	//3.表单验证
	if !dao.IsPhoneExist(phone) { //手机号未注册
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "用户不存在")
		return
	}
	user := &model.User{}
	user, _ = dao.GetUserByPhone(phone)

	isError := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) //将前端的密码和数据库的加密之后的密码进行验证
	if isError != nil {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码错误")
		return
	}

	//4.发放token

	token, err := common.ReleaseToken(user)
	if err != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "系统错误")
	}

	//5.返回结果
	response.Success(ctx, gin.H{"token": token}, "登陆成功")
}

func Info(ctx *gin.Context) {
	//获取信息
	user, isExist := ctx.Get("user")
	if !isExist {
		response.Response(ctx, http.StatusNotFound, 403, nil, "用户不存在")
		return
	}
	//5.返回信息
	response.Success(ctx, gin.H{"user": dto.ToUserDto(user.(model.User))}, "获取信息成功")
}
